import 'package:flutter/material.dart';

// 标签类
class Tag {
  final String name; // 标签名
  final int categoryId; // 分类编号

  Tag({
    required this.name,
    required this.categoryId,
  });
}

// 菜单抽屉
class MenuDrawer extends StatefulWidget {
  final List<Tag> data; // 选项的列表
  final Widget? icon; // 组件的图标

  const MenuDrawer({
    super.key,
    required this.data,
    this.icon,
  });

  @override
  State<MenuDrawer> createState() => _MenuDrawerState();
}

class _MenuDrawerState extends State<MenuDrawer> {
  // 默认菜单抽屉关闭
  bool _isOpen = false;

  OverlayState? _overlayState;
  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    // 1、获取OverlayState
    _overlayState = Overlay.of(context);
  }

  // 控制菜单抽屉的状态
  void controlMenuBox() {
    if (!_isOpen) {
      showMenuBox();
    } else {
      closeMenuBox();
    }
  }

  // 关闭抽屉盒子
  void closeMenuBox() {
    if (_overlayState != null) {
      _overlayEntry?.remove();
      setState(() {
        _isOpen = false;
      });
    }
  }

  // 打开抽屉盒子
  void showMenuBox() {
    RenderBox? renderBox = context.findRenderObject() as RenderBox;
    var centerPosition = renderBox.size.center(Offset.zero); // 菜单按钮自身的中点的坐标
    var globalCenterPosition =
    renderBox.localToGlobal(centerPosition); // 菜单按钮全局的中点的坐标
    var positionedCenterLineX =
        globalCenterPosition.dx; // Positioned组件中线在x轴上的位置

    var mediaQuery = MediaQuery.of(context); // 获取屏幕信息
    var appTopPadding = mediaQuery.padding.top; // 手机刘海高度
    var mediaWidth = mediaQuery.size.width; // 获取屏幕宽度
    var bottomNavigationBar = 77.0; // bottomNavigationBar 高度为77 通过GlobalKey得到的
    var appBarHeight = 60.0; // 这个高度是自己给的 appBar也不是内置的那个而是使用Container代替的

    var optionTagWidth = 54.0; // 子组件标签的宽度 通过GlobalKey得到的

    var positionedTop = appTopPadding + appBarHeight; // 覆盖层Positioned组件距离顶部的距离
    var positionedLeft =
        positionedCenterLineX - optionTagWidth / 2; // 覆盖层Positioned组件距离左边的距离
    var positionedRight = mediaWidth -
        (positionedCenterLineX + optionTagWidth / 2); // 覆盖层Positioned组件距离右边的距离
    var positionedBottom = bottomNavigationBar + 10; // 覆盖层Positioned组件距离底部的距离

    // 如果overlayState不为空且子组件存在时
    if (_overlayState != null && widget.data.isNotEmpty) {
      setState(() {
        _isOpen = true;
      });
      // 2、创建OverlayEntry遮罩层入口
      _overlayEntry = OverlayEntry(
        builder: (context) {
          return MenuDrawerOverlay(
            top: positionedTop,
            bottom: positionedBottom,
            left: positionedLeft,
            right: positionedRight,
            onPressed: closeMenuBox,
            data: widget.data,
          );
        },
      );
      // 3、插入OverlayEntry
      _overlayState?.insert(_overlayEntry!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: controlMenuBox,
      icon: widget.icon ?? const Icon(Icons.menu),
    );
  }
}

class MenuDrawerOverlay extends StatefulWidget {
  final List<Tag> data; // 选项的列表
  final double top; // Positioned组件的top
  final double bottom; // Positioned组件的bottom
  final double left; // Positioned组件的left
  final double right; // Positioned组件的right
  final VoidCallback onPressed; // 回调
  final double? radius; // 圆角
  final EdgeInsetsGeometry? padding; // 内边距

  const MenuDrawerOverlay({
    super.key,
    required this.top,
    required this.bottom,
    required this.left,
    required this.right,
    required this.onPressed,
    this.radius,
    this.padding,
    required this.data,
  });

  @override
  State<MenuDrawerOverlay> createState() => _MenuDrawerOverlayState();
}

class _MenuDrawerOverlayState extends State<MenuDrawerOverlay> {
  late double _maxListViewHeight; // ListView的最大高度
  late double _listViewHeight; // ListView的高度
  late int optionTagNum; // 子组件标签的数量

  int selectedIndex = 0; // 标签选择索引值 默认选中第一个
  List<Tag> tags = []; // 标签列表

  // 获取ListView的高度，根据标签的高度动态调整
  double _getListViewHeight() {
    double totalHeight = 0.0;
    for (int i = 0; i < optionTagNum; i++) {
      if (tags[i].name.characters.length < 4) {
        totalHeight += 28.0; // 一行的标签高度是28.0
      } else {
        totalHeight += 46.0; // 两行的标签高度是46.0
      }
    }
    return totalHeight;
  }

  @override
  void initState() {
    tags = widget.data;
    optionTagNum = tags.length;
    _listViewHeight = _getListViewHeight();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 手势占满整个屏幕，置于最底层
        GestureDetector(onTap: widget.onPressed),
        Positioned(
          top: widget.top,
          bottom: widget.bottom,
          left: widget.left,
          right: widget.right,
          child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              _maxListViewHeight = constraints.maxHeight * 7 / 10;
              return Container(
                padding: widget.padding ?? const EdgeInsets.only(top: 20),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(widget.radius ?? 40),
                  gradient: const LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xffbe7634), // 渐变色起始颜色
                      Color(0xfff4e8df), // 渐变色结束颜色
                    ],
                  ),
                ),
                child: Column(
                  children: [
                    SizedBox(
                      height: _listViewHeight < _maxListViewHeight
                          ? _listViewHeight
                          : _maxListViewHeight,
                      child: ListView.builder(
                        physics: _listViewHeight < _maxListViewHeight
                            ? const NeverScrollableScrollPhysics()
                            : null,
                        padding: const EdgeInsets.all(0),
                        itemCount: optionTagNum,
                        itemBuilder: (BuildContext context, int index) {
                          return GestureDetector(
                            onTap: () {
                              setState(() {
                                selectedIndex = index; // 更新选中的索引
                                print("跳转页面：${tags[index].categoryId}");
                              });
                            },
                            child: MenuDrawerOptionTag(
                              tag: tags[index],
                              isSelected: selectedIndex == index,
                            ),
                          );
                        },
                      ),
                    ),
                    // 添加标签按钮
                    IconButton(
                      onPressed: () {},
                      icon: const Icon(
                        Icons.add,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}

// 菜单抽屉的选项标签
class MenuDrawerOptionTag extends StatefulWidget {
  final Tag tag; // 标签内容
  final Color? selectedColor; // 选中颜色
  final double? fontSize; // 字体大小
  final bool? isSelected; // 是否选中

  const MenuDrawerOptionTag({
    super.key,
    required this.tag,
    this.selectedColor,
    this.fontSize,
    this.isSelected,
  });

  @override
  State<MenuDrawerOptionTag> createState() => _MenuDrawerOptionTagState();
}

class _MenuDrawerOptionTagState extends State<MenuDrawerOptionTag> {
  @override
  Widget build(BuildContext context) {
    String name = widget.tag.name;
    double? size = widget.fontSize;
    int count = name.characters.length; // 获取字符串的字符个数
    int line; // 行数

    // 最多6个字符，多余的裁剪掉
    if (count > 6) {
      name = name.characters.take(6).join();
    }

    // 当字符串的字符个数为4时，显示两个后换行
    if (count == 4) {
      name = "${name.substring(0, 2)}\n${name.substring(2, 4)}";
    }

    // 当字符个数小于4时，也就是1~3个字符时，为1行 大于等于4时，为2行
    if (count < 4) {
      line = 1;
    } else {
      line = 2;
    }

    return Container(
      // 使的标签和标签直接有点间距
      margin: const EdgeInsets.symmetric(horizontal: 3,vertical: 5),
      // *1.2是行高
      height: (size ?? 15) * 1.2 * line,
      // *3是一行最多三个文字
      width: ((size ?? 15) + 1) * 3,
      alignment: Alignment.center,
      child: Text(
        name,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: widget.isSelected ?? false
              ? widget.selectedColor ?? Colors.black
              : Colors.white,
          fontSize: size ?? 15,
          height: 1.2, // 设置行高
          decoration: TextDecoration.none, // 去除下划线
        ),
      ),
    );
  }
}